<?php

class DegreesOfSeparationController extends Controller {

	protected $db;
	
	function __construct($db) {
	
		$this->db = $db;
		
		$this->view = new DegreesOfSeparationView();
		$this->view->setAList($this->getActors());
		$this->view->setTitle('Degrees of Separation');
		
		if (isset($_POST['action'])) {
			$this->view->setDegree($this->determineDistance($_POST['actorID1'], $_POST['actorID2']));
		}
	}
	
	
	function determineDistance($sourceId, $targetId) {
		$serializer = new Serializer();
		$curDistance = 0;
		$openStates = array();
		$visitedStates = array();
		$openStates[0] = $serializer->serialize($curDistance, $sourceId);
		while (!empty($openStates)) {
			//get First open state, with the minimum distance. Consider it visited. Then generate successors
			$min = 1000;	//we just suppose that there is no 1000-degree of separation
			foreach ($openStates as $oState) {
				$dist = $serializer->getDistance($oState);
				if ($dist < $min) {
					$min = $dist;
					$curState = $oState;
				}
			}	
			$curState = $openStates[0];
			array_shift($openStates);
			array_push($visitedStates, $serializer->getLabel($curState));
			$aList = $this->getAssociatedActors($serializer->getLabel($curState));
			if ($serializer->getDistance($curState)+1 < 8) {
				foreach ($aList as $nState) {
					//if it is goal state then return distance (which is the demanded degree of separation)
					if ($nState == $targetId) {
						return $serializer->getDistance($curState)+1;
					}
					//if it is already a visited state, throw it away
					if (!in_array($nState, $visitedStates)){
						array_push($openStates, $serializer->serialize($serializer->getDistance($curState)+1, $nState));
					}
				}
			}
		}
		
		return -1;
	}
	
	function getAssociatedActors($id) {
		$results = $this->db->getAssociatedActors($id);
		$aList = array();
		$i=0;
		while ($row = $results->fetch_row()) {
			$a = $row[0];
			$aList[$i] = $a;
			$i++;
		}
		return $aList;
	}
	
	function getActors() {
		$results = $this->db->getActors();
		$aList = array();
		$i=0;
		while ($row = $results->fetch_row()) {
			$a = new Actor($row[0], $row[1], $row[2], true);
			$aList[$i] = $a;
			$i++;
		}
		return $aList;
	}
	
	
	
}